package com.kyh.util.wxPay;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XmlUtil {
	/**
	 * xml to map
	 * @param xmlStr
	 * @return
	 */
	public static Map<String,Object> xmlStr2Map(String xmlStr){
		Map<String,Object> map = new HashMap<String,Object>();
		Document doc;
		try {
			doc = DocumentHelper.parseText(xmlStr);
	        Element root = doc.getRootElement();  
	        List children = root.elements();  
	        if(children != null && children.size() > 0) {  
	            for(int i = 0; i < children.size(); i++) {  
	                Element child = (Element)children.get(i);  
	                map.put(child.getName(), child.getTextTrim());  
	            }  
	        }  
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}
	
	 /**
	  * 
	  * Map转xml数据
	  */
	 public static String mapToXML(Map<String,String> param){
		 StringBuffer sb = new StringBuffer();
		 sb.append("<xml>");
		 for (Map.Entry<String,String> entry : param.entrySet()) { 
			    sb.append("<"+ entry.getKey() +">");
			    sb.append(entry.getValue());
			    sb.append("</"+ entry.getKey() +">");
		}  
		 sb.append("</xml>");
		 return sb.toString();
	 }
	 
	 public static String setWeChatXML(String return_code, String return_msg) {
	        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
	 }
}
